#!/usr/bin/env python
"""
FrontEnd.py

This is the main GUI class. It initialises most things, but calls separate
modules to draw the various options on the right panel.

"""

def _(s): return s

from conf import Apache
from ..utils import ImportHandler
from ..dialogs import UserMessage
from ..settings import UserSettings
from ..databases import DatabaseMgr
import HistoryHandler, MenuHandler, ToolbarHandler, Sites
import os, sys, wx

class FrontEnd(wx.Frame):
    """
    This is the main gui class.
    """
    def __init__(self, file, wsize, wposition):
        wx.Frame.__init__(self, None, -1, "Athabaskan", size=wsize,
                          style=wx.DEFAULT_FRAME_STYLE |
                                  wx.NO_FULL_REPAINT_ON_RESIZE |
                                  wx.MAXIMIZE)
        self.Centre(wposition)
        self.SetIcon(wx.Icon("images/athabaskan_icon.xpm", wx.BITMAP_TYPE_XPM))
        self.fileSaved = True
        self.userSettings = UserSettings.UserSettings().setState()
        self.CreateStatusBar(1, wx.ST_SIZEGRIP)
        importHandler = ImportHandler.ImportHandler().setState(self)
        MenuHandler.MenuHandler().setState(self).doMenu()
        ToolbarHandler.ToolbarHandler().setState(self).doToolbar()
        HistoryHandler.HistoryHandler().setState().updateMenu()
        importHandler.bindExtraEvents()
        self.currentFile = file
        self.loadInfo(file)
        self.Show(True)
        self.userSettings.anyErrors()
    
    def loadInfo(self, file):
        try:
            apache = Apache.Apache(file)
            dir = apache.get_directive("DocumentRoot").args.strip('"')
            self.currentFile = file
            HistoryHandler.HistoryHandler().AddFileToHistory(file)
            self.SetTitle(file)
            self.fileSaved = True
            names = os.listdir(dir)
            files = [os.path.join(dir, file) for file in names]
            files = [d for d in files if os.path.isdir(d)]
            if hasattr(self, "sites"):
                self.sites.Destroy()
                del self.sites
            self.sites = Sites.Sites(self, files, names)
            menuSet = MenuHandler.MenuHandler.MENU_NON_ESSENTIAL
            MenuHandler.MenuHandler().setEnabled(menuSet, True)
            return True
        except (OSError, IOError, TypeError), err:
            if hasattr(self, "sites"):
                UserMessage.say(err, _("Error!"), wx.ICON_ERROR)
            else:
                menuSet = MenuHandler.MenuHandler.MENU_NON_ESSENTIAL
                MenuHandler.MenuHandler().setEnabled(menuSet, False)
            return False
    